package com.example.controller;


import com.example.entity.User;
import com.example.mapper.UserDao;
import com.example.result.Code;
import com.example.result.R;
import com.example.service.UserService;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 柳飞宇
 * @since 2022-9-10666666666666666666
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserService service;

    @GetMapping("queryAll")
    public R queryAll(){
        //List<User> list = service.list(null);
        List<User> userList = userDao.selectList(null);
        boolean flag=null==userList?false:true;
        return new R(flag?Code.SUCCESS:Code.ERROR,userList,flag?"查询成功！":"查询失败 ！");
    }

    @GetMapping("queryById/{id}")
    public R queryById(@PathVariable Integer id){
        User user = service.getById(id);
        boolean flag=null==user?false:true;
        return new R(flag?Code.SUCCESS:Code.ERROR,user,flag?"查询成功！":"查询失败！");
    }

    @GetMapping("queryByIds")
    public R queryByIds(@RequestBody List<String> list){
       // List<User> users = userDao.selectBatchIds(list);
        List<User> users = service.listByIds(list);
        boolean flag=null==users?false:true;
        return new R(flag?Code.SUCCESS:Code.ERROR,users,flag?"查询成功！":"查询失败！");
    }

    @PostMapping("save")
    public R save(@RequestBody User user){
        //int insert = userDao.insert(user);
        boolean save = service.save(user);
        return new R(save? Code.SUCCESS:Code.ERROR,save?"添加成功":"添加失败");
    }

    @PutMapping("update")
    public R update(@RequestBody User user){
        boolean flag = service.updateById(user);
        return new R(flag?Code.SUCCESS:Code.ERROR,flag?"更新成功":"更新失败");
    }

    @DeleteMapping("delete/{id}")
    public R deleteById(@PathVariable Integer id){
        boolean flag = service.removeById(id);
        return new R(flag?Code.SUCCESS:Code.ERROR,flag?"删除成功":"删除失败");
    }

    @DeleteMapping("deleteByName/{name}")//若为名字为中文postman里路径写的时候名字不能加""
    public R deleteByName(@PathVariable("name") String name){
        boolean flag = service.removeByName(name);
        return new R(flag?Code.SUCCESS:Code.ERROR,flag?"删除成功":"删除失败");
    }

}

